#include "fcgio.h"
#include "fcgiapp.h"
#include "echo.h"
#include <stdlib.h>


using namespace std;
int MessagePump( char **envp );

int main( void )
{
	streambuf *cin_streambuf  = cin.rdbuf();
	streambuf *cout_streambuf = cout.rdbuf();
	streambuf *cerr_streambuf = cerr.rdbuf();

	FCGX_Request request;

	FCGX_Init();
	FCGX_InitRequest( &request, 0, 0 );

	while( FCGX_Accept_r( &request ) == 0 )	{
		fcgi_streambuf cin_fcgi_streambuf( request.in );
		fcgi_streambuf cout_fcgi_streambuf( request.out );
		fcgi_streambuf cerr_fcgi_streambuf( request.err );

#if HAVE_IOSTREAM_WITHASSIGN_STREAMBUF
		cin  = &cin_fcgi_streambuf;
		cout = &cout_fcgi_streambuf;
		cerr = &cerr_fcgi_streambuf;
#else
		cin.rdbuf( &cin_fcgi_streambuf );
		cout.rdbuf( &cout_fcgi_streambuf );
		cerr.rdbuf( &cerr_fcgi_streambuf );
#endif

		MessagePump( request.envp );
		echo( request ); // echo Server Environment
	}

#if HAVE_IOSTREAM_WITHASSIGN_STREAMBUF
	cin  = cin_streambuf;
	cout = cout_streambuf;
	cerr = cerr_streambuf;
#else
	cin.rdbuf( cin_streambuf );
	cout.rdbuf( cout_streambuf );
	cerr.rdbuf( cerr_streambuf );
#endif

	return 0;
}

int MessagePump( FCGX_ParamArray envp )
{
	const char *cHost = FCGX_GetParam( "HTTP_HOST", envp );

	cout << "HTTP_HOST:" << cHost << endl;

	return 0;
}

